package com.jjiang.bbmall.order.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jjiang.bbmall.order.constant.OrderConstant;
import com.jjiang.bbmall.order.dao.OrderDao;
import com.jjiang.bbmall.order.entity.OrderEntity;
import com.jjiang.bbmall.order.entity.OrderItemEntity;
import com.jjiang.bbmall.order.entity.PaymentInfoEntity;
import com.jjiang.bbmall.order.enume.OrderStatusEnum;
import com.jjiang.bbmall.order.enume.SubmitStatusEnum;
import com.jjiang.bbmall.order.exception.NoStockException;
import com.jjiang.bbmall.order.feign.CartFeignService;
import com.jjiang.bbmall.order.feign.MemberFeignService;
import com.jjiang.bbmall.order.feign.ProductFeignService;
import com.jjiang.bbmall.order.feign.WmsFeignService;
import com.jjiang.bbmall.order.interceptor.LoginUserInterceptor;
import com.jjiang.bbmall.order.service.OrderItemService;
import com.jjiang.bbmall.order.service.OrderService;
import com.jjiang.bbmall.order.service.PaymentInfoService;
import com.jjiang.bbmall.order.vo.*;
import com.jjiang.common.to.SeckillOrderTo;
import com.jjiang.common.to.SkuHasStockTo;
import com.jjiang.common.utils.PageUtils;
import com.jjiang.common.utils.Query;
import com.jjiang.common.utils.R;
import com.jjiang.common.vo.MemberEntityVo;
import com.jjiang.common.to.OrderTo;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {

    private final ThreadLocal<OrderSubmitVo> orderSubmitVoThreadLocal = new ThreadLocal<>();

    @Autowired
    PaymentInfoService paymentInfoService;

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Autowired
    OrderItemService orderItemService;

    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    MemberFeignService memberFeignService;

    @Autowired
    CartFeignService cartFeignService;

    @Autowired
    WmsFeignService wmsFeignService;

    @Autowired
    ThreadPoolExecutor threadPoolExecutor;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public OrderConfirmVo confirmOrder() {
        // 解决feign接口进行远程【异步】调用时，请求头丢失的问题
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();

        OrderConfirmVo orderConfirmVo = new OrderConfirmVo();
        MemberEntityVo memberEntityVo = LoginUserInterceptor.loginUser.get();
        // 1. 远程查询所有收获地址列表
        CompletableFuture<Void> getAddressFuture = CompletableFuture.runAsync(() -> {
            RequestContextHolder.setRequestAttributes(requestAttributes);
            List<MemberReceiveAddressVo> addresses = memberFeignService.getAddresses(memberEntityVo.getId());
            orderConfirmVo.setAddress(addresses);
        }, threadPoolExecutor);

        // feign在远程调用时要自动调用拦截器
        // 浏览器是自动携带cookie的；feign远程调用会新创建一个request，会丢失请求头，也不携带cookie，认为没有登录；
        // 因此需要加入feign远程调用的请求拦截器

        // 2. 查询购物车选中的购物项
        CompletableFuture<Void> cartFuture = CompletableFuture.runAsync(() -> {
            RequestContextHolder.setRequestAttributes(requestAttributes);
            List<OrderItemVo> items = cartFeignService.currentUserCartItems();
            orderConfirmVo.setItems(items);
        }, threadPoolExecutor).thenRunAsync(() -> {
            List<OrderItemVo> items = orderConfirmVo.getItems();
            // 批量查询每个商品的信息
            List<Long> collect = items.stream().map(OrderItemVo::getSkuId).collect(Collectors.toList());
            R r = wmsFeignService.getSkuHasStock(collect);
            if (r.getCode() == 0) {
                List<SkuHasStockTo> data = r.getData(new TypeReference<List<SkuHasStockTo>>() {
                });
                if (data != null && data.size() != 0) {
                    Map<Long, Boolean> stocks = data.stream().collect(Collectors.toMap(SkuHasStockTo::getSkuId, SkuHasStockTo::getHasStock));
                    orderConfirmVo.setStocks(stocks);
                }
            }
        }, threadPoolExecutor);

        // 3. 查询用户积分
        orderConfirmVo.setIntegration(memberEntityVo.getIntegration());

        // 4. 其余的自动计算

        // 5. 设置防重令牌
        String token = UUID.randomUUID().toString().replace("-", "");
        orderConfirmVo.setOrderToken(token);

        String tokenName = OrderConstant.USER_ORDER_TOKEN_PREFIX + memberEntityVo.getId();
        redisTemplate.opsForValue().set(tokenName, token, 30, TimeUnit.MINUTES);

        // 等待异步任务完成，再返回
        CompletableFuture<Void> future = CompletableFuture.allOf(getAddressFuture, cartFuture);
        try {
            future.get();
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }

        return orderConfirmVo;
    }

    //    @GlobalTransactional
    @Transactional
    @Override
    public SubmitOrderResponseVo submitOrder(OrderSubmitVo orderSubmitVo) {
        orderSubmitVoThreadLocal.set(orderSubmitVo);
        SubmitOrderResponseVo responseVo = new SubmitOrderResponseVo();
        // 进行下单；创建订单；验证令牌；验证价格；锁定库存
        // 获取当前登录的用户
        MemberEntityVo memberEntityVo = LoginUserInterceptor.loginUser.get();
        // 1.验证令牌【令牌的验证和删除必须是原子操作】，脚本返回0:失败；1:成功
        String luaScript = "if redis.call('get', KEYS[1])==ARGV[1] then return redis.call('del',KEYS[1]) else return 0 end";
        String orderToken = orderSubmitVo.getOrderToken();
        String tokenName = OrderConstant.USER_ORDER_TOKEN_PREFIX + memberEntityVo.getId();
        Long result = redisTemplate.execute(new DefaultRedisScript<Long>(luaScript, Long.class), Collections.singletonList(tokenName), orderToken);
        if (result == null || result == 0L) {
            // 验证令牌不通过
            responseVo.setCode(SubmitStatusEnum.TOKEN_ERROR.getCode());
            return responseVo;
        }
        // 验证令牌成功
        // 2.创建订单
        OrderCreateTO order = createOrder();
        // 3.验证价格
        BigDecimal payAmount = order.getOrder().getPayAmount();
        BigDecimal payPrice = orderSubmitVo.getPayPrice();
        double minus = Math.abs(payAmount.subtract(payPrice).doubleValue());
        if (minus >= 0.01) {
            // 对比失败
            responseVo.setCode(SubmitStatusEnum.PRICE_ERROR.getCode());
            return responseVo;
        }
        // 对比成功
        // 4.设置其他信息
        // 设置订单的会员id
        order.getOrder().setMemberId(memberEntityVo.getId());
        order.getOrder().setMemberUsername(memberEntityVo.getUsername());
        // 5.保存订单
        saveOrder(order);
        // 6.锁定库存。只要有异常就回滚数据
        // 在高并发场景下不使用@GlobalTransactional，因为性能较差
        // 使用通知的方式通知其他服务【使用消息队列】，让服务自动解锁库存
        WareSkuLockVo lockVo = new WareSkuLockVo();
        lockVo.setOrderSn(order.getOrder().getOrderSn());
        List<OrderItemVo> collect = order.getItems().stream().map(item -> {
            OrderItemVo orderItemVo = new OrderItemVo();
            orderItemVo.setSkuId(item.getSkuId());
            orderItemVo.setCount(item.getSkuQuantity());
            orderItemVo.setTitle(item.getSkuName());
            orderItemVo.setPrice(item.getSkuPrice());
            return orderItemVo;
        }).collect(Collectors.toList());
        lockVo.setLocks(collect);
        R r = wmsFeignService.orderLockStock(lockVo);
        if (r.getCode() != 0) {
            // 【存在分布式事务问题】
            // 锁定失败
            throw new NoStockException();
        }
        // 判断锁定成功
        responseVo.setOrder(order.getOrder());
        responseVo.setCode(SubmitStatusEnum.SUCCESS.getCode());
        // 订单创建成功，发送消息给mq
        rabbitTemplate.convertAndSend("order-event-exchange", "order.create.order", order.getOrder());
        return responseVo;
    }

    @Override
    public OrderEntity getOrderByOrderSn(String orderSn) {
        return this.getOne(new QueryWrapper<OrderEntity>().eq("order_sn", orderSn));
    }

    @Override
    public Boolean closeOrder(OrderEntity entity) {
        // 需要查询当前订单的状态
        OrderEntity byId = this.getById(entity.getId());
        if (byId != null && Objects.equals(byId.getStatus(), OrderStatusEnum.CREATE_NEW.getCode())) {
            // 待付款的，超时了才会关闭订单
            OrderEntity changeOrder = new OrderEntity();
            changeOrder.setId(entity.getId());
            changeOrder.setStatus(OrderStatusEnum.CANCELED.getCode());
            changeOrder.setModifyTime(new Date());
            this.updateById(changeOrder);
            // 需要重新查询最新的订单信息
            OrderEntity newEntity = this.getById(changeOrder.getId());
            OrderTo orderTo = new OrderTo();
            BeanUtils.copyProperties(newEntity, orderTo);
            // 关闭订单成功，需要再次发送消息给库存解锁
            // 需要保证每个发送的消息都要发送成功，需要进行日志记录【保存到数据库】。
            // 定期扫描数据库，再次发送失败的消息
            rabbitTemplate.convertAndSend("order-event-exchange", "order.release.other", orderTo);
        }
        return false;
    }

    @Override
    public PageUtils queryPageWithItem(Map<String, Object> params) {
        MemberEntityVo memberEntityVo = LoginUserInterceptor.loginUser.get();
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>().eq("member_id", memberEntityVo.getId()).orderByDesc("id")
        );
        List<OrderEntity> orderEntities = page.getRecords().stream().map(order -> {
            List<OrderItemEntity> orderItemEntities = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", order.getOrderSn()));
            order.setItemEntities(orderItemEntities);
            return order;
        }).collect(Collectors.toList());
        page.setRecords(orderEntities);

        return new PageUtils(page);
    }

    @Override
    public Boolean handlePayResult(String orderSn) {
        // 1.保存交易流水
        PaymentInfoEntity infoEntity = new PaymentInfoEntity();
        infoEntity.setOrderSn(orderSn);
        infoEntity.setPaymentStatus("success");
        infoEntity.setCallbackTime(new Date());
        paymentInfoService.save(infoEntity);
        // 2.修改订单状态信息
        Integer count = this.baseMapper.updateOrderStatus(orderSn, OrderStatusEnum.PAYED.getCode());
        return count == 1;
    }

    @Override
    public Boolean createSeckillOrder(SeckillOrderTo seckillOrderTo) {
        //保存订单信息
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOrderSn(seckillOrderTo.getOrderSn());
        orderEntity.setMemberId(seckillOrderTo.getMemberId());
        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        BigDecimal seckillTotalAmount = seckillOrderTo.getSkuRelationVo().getSeckillPrice().multiply(new BigDecimal(seckillOrderTo.getNum().toString()));
        orderEntity.setPayAmount(seckillTotalAmount);
        //保存
        this.save(orderEntity);
        //保存订单项信息
        OrderItemEntity orderItemEntity = new OrderItemEntity();
        orderItemEntity.setOrderSn(seckillOrderTo.getOrderSn());
        orderItemEntity.setRealAmount(seckillTotalAmount);
        orderItemEntity.setSkuQuantity(seckillOrderTo.getNum());
        orderItemEntity.setSkuPic(seckillOrderTo.getSkuInfoVo().getSkuDefaultImg());
        orderItemEntity.setSkuName(seckillOrderTo.getSkuInfoVo().getSkuName());
        orderItemService.save(orderItemEntity);
        return false;
    }

    /**
     * 保存订单
     *
     * @param order
     */
    private void saveOrder(OrderCreateTO order) {
        // 保存订单
        OrderEntity orderEntity = order.getOrder();
        orderEntity.setCreateTime(new Date());
        orderEntity.setModifyTime(new Date());
        this.save(orderEntity);

        // 保存订单项
        List<OrderItemEntity> items = order.getItems();
        orderItemService.saveBatch(items);

    }

    /**
     * 创建订单
     *
     * @return
     */
    private OrderCreateTO createOrder() {
        OrderSubmitVo submitVo = orderSubmitVoThreadLocal.get();
        OrderCreateTO orderCreateTO = new OrderCreateTO();
        // 1. 生成订单号
        String orderSn = IdWorker.getTimeId();
        // 2. 填充收货地址和运费信息
        OrderEntity orderEntity = buildOrder(submitVo);
        orderEntity.setOrderSn(orderSn);
        orderCreateTO.setOrder(orderEntity);
        // 3. 获取订单项
        List<OrderItemEntity> orderItemEntities = buildOrderItems(orderSn);
        orderCreateTO.setItems(orderItemEntities);
        // 4. 验价格
        computePrice(orderEntity, orderItemEntities);

        return orderCreateTO;
    }

    /**
     * 验价
     *
     * @param orderEntity
     * @param orderItemEntities
     */
    private void computePrice(OrderEntity orderEntity, List<OrderItemEntity> orderItemEntities) {
        // 1.订单价格相关
        // 设置订单总额
        BigDecimal totalPrice = new BigDecimal("0.00");
        BigDecimal couponPrice = new BigDecimal("0.00");
        BigDecimal integrationPrice = new BigDecimal("0.00");
        BigDecimal promotionPrice = new BigDecimal("0.00");
        Integer giftIntegration = 0;
        Integer giftGrowth = 0;

        for (OrderItemEntity orderItemEntity : orderItemEntities) {
            totalPrice = totalPrice.add(orderItemEntity.getRealAmount());
            couponPrice = couponPrice.add(orderItemEntity.getCouponAmount());
            integrationPrice = integrationPrice.add(orderItemEntity.getIntegrationAmount());
            promotionPrice = promotionPrice.add(orderItemEntity.getPromotionAmount());
            giftIntegration += orderItemEntity.getGiftIntegration();
            giftGrowth += orderItemEntity.getGiftGrowth();
        }
        orderEntity.setTotalAmount(totalPrice);
        // 设置订单应付的金额
        orderEntity.setPayAmount(orderEntity.getTotalAmount().add(orderEntity.getFreightAmount()));
        // 设置订单其他优惠金额
        orderEntity.setCouponAmount(couponPrice);
        orderEntity.setIntegrationAmount(integrationPrice);
        orderEntity.setPromotionAmount(promotionPrice);
        // 设置获得的积分与成长值
        orderEntity.setIntegration(giftIntegration);
        orderEntity.setGrowth(giftGrowth);
        // 设置订单删除状态为未删除
        orderEntity.setDeleteStatus(0);
    }

    /**
     * 构建所有订单项目
     *
     * @return 所有订单项目
     */
    private List<OrderItemEntity> buildOrderItems(String orderSn) {
        List<OrderItemEntity> orderItemEntities = null;
        List<OrderItemVo> items = cartFeignService.currentUserCartItems();
        if (items != null && items.size() > 0) {
            orderItemEntities = items.stream().map(cartItem -> buildOrderItem(cartItem, orderSn)).collect(Collectors.toList());
        }
        return orderItemEntities;
    }

    /**
     * 构建单个订单项，最后回确定订单价格
     *
     * @param cartItem 购物车项
     * @return 订单项
     */
    private OrderItemEntity buildOrderItem(OrderItemVo cartItem, String orderSn) {
        OrderItemEntity orderItemEntity = new OrderItemEntity();
        // 1. 设置订单号
        orderItemEntity.setOrderSn(orderSn);
        // 2. 设置sku信息
        orderItemEntity.setSkuId(cartItem.getSkuId());
        orderItemEntity.setSkuName(cartItem.getTitle());
        orderItemEntity.setSkuPic(cartItem.getImage());
        orderItemEntity.setSkuPrice(cartItem.getPrice());
        String skuAttrsVals = StringUtils.collectionToDelimitedString(cartItem.getSkuAttr(), "；");
        orderItemEntity.setSkuAttrsVals(skuAttrsVals);
        orderItemEntity.setSkuQuantity(cartItem.getCount());
        // 3. 设置spu信息
        // 需要远程查询
        R r = productFeignService.getSpuInfoBySkuId(cartItem.getSkuId());
        if (r.getCode() == 0) {
            SpuInfoEntityVo spuInfoEntityVo = r.getData(new TypeReference<SpuInfoEntityVo>() {
            });
            // 设置spu信息
            orderItemEntity.setSpuId(spuInfoEntityVo.getId());
            orderItemEntity.setSpuBrand(spuInfoEntityVo.getBrandId().toString());
            orderItemEntity.setSpuName(spuInfoEntityVo.getSpuName());
            orderItemEntity.setCategoryId(spuInfoEntityVo.getCatalogId());
        }

        // 4. 优惠信息【暂时不做】

        // 5. 积分信息
        orderItemEntity.setGiftGrowth(cartItem.getTotalPrice().intValue());
        orderItemEntity.setGiftIntegration(cartItem.getTotalPrice().intValue());

        // 6. 设置总价格
        orderItemEntity.setPromotionAmount(new BigDecimal("0"));
        orderItemEntity.setCouponAmount(new BigDecimal("0"));
        orderItemEntity.setIntegrationAmount(new BigDecimal("0"));
        BigDecimal totalPrice = cartItem.getTotalPrice();
        BigDecimal realAmount = totalPrice.subtract(orderItemEntity.getPromotionAmount()).subtract(orderItemEntity.getCouponAmount()).subtract(orderItemEntity.getIntegrationAmount());
        orderItemEntity.setRealAmount(realAmount);
        return orderItemEntity;
    }

    /**
     * 构建订单
     *
     * @param submitVo 提交的订单
     * @return 构建的订单实体类
     */
    private OrderEntity buildOrder(OrderSubmitVo submitVo) {
        OrderEntity orderEntity = new OrderEntity();
        R r = wmsFeignService.getFare(submitVo.getAddrId());
        if (r.getCode() == 0) {
            FareVo fareVo = r.getData("data", new TypeReference<FareVo>() {
            });
            // 运费信息
            orderEntity.setFreightAmount(fareVo.getFare());
            MemberReceiveAddressVo address = fareVo.getAddress();
            // 收货地址
            orderEntity.setReceiverName(address.getName());
            orderEntity.setReceiverPhone(address.getPhone());
            orderEntity.setReceiverPostCode(address.getPostCode());
            orderEntity.setReceiverProvince(address.getProvince());
            orderEntity.setReceiverCity(address.getCity());
            orderEntity.setReceiverRegion(address.getRegion());
            orderEntity.setReceiverDetailAddress(address.getDetailAddress());
            // 订单状态
            orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
            // 设置自动确认时间
            orderEntity.setAutoConfirmDay(7);
        }
        return orderEntity;
    }

}
